﻿using Masa.BuildingBlocks.Dispatcher.Events;
using Masa.Contrib.Dispatcher.Events;
using Masa.CqrsProject.Commands;
using Masa.CqrsProject.Contexts;
using Masa.CqrsProject.Models;
using Masa.CqrsProject.Repositorys;

namespace Masa.CqrsProject.Handlers
{

    /// <summary>
    /// 订单处理类
    /// </summary>
    public class OrderCommandHandler
    {
        private IOrderRepository _OrderRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderRepository"></param>
        public OrderCommandHandler(IOrderRepository orderRepository)
        {
            _OrderRepository = orderRepository;
        }

        /// <summary>
        /// 创建订单处理方法
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [EventHandler]
        public async Task CreateOrder(CreateOrderCommand command)
        {
            Console.WriteLine("创建订单处理...");
            //1、查询订单
            OrderInfo order = await _OrderRepository.GetOrderAsync(command.OrderInfo.OrderSn);
            if (order != null)
            {
                throw new Exception("订单号不能重复");
            }

            //2、添加订单
            await _OrderRepository.CreateAsync(command.OrderInfo);
        }

        /// <summary>
        /// 更新订单处理方法
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [EventHandler]
        public async Task UpdateOrder(UpdateOrderCommand command)
        {
            const string message = "更新订单处理...";
            OrderInfo order = await _OrderRepository.GetOrderAsync(command.Id.ToString());
            if (order != null)
            {
                order.OrderSn = command.OrderInfo.OrderSn;
                order.OrderItems = command.OrderInfo.OrderItems;
                await _OrderRepository.UpdateAsync(order);
            }
        }

        /// <summary>
        /// 删除订单处理方法
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [EventHandler]
        public async Task DeleteAsync(DeleteOrderCommand command)
        {
            Console.WriteLine("删除订单处理...");
            //1、删除订单
            await _OrderRepository.DeleteAsync(command.Id);
        }


    }
}
